const fs =require('fs')
const path = require('path')
// 解析文件请求体配置
const multer = require('multer')
const upload = multer()
// 文件名转换
const mime = require('mime-types')
const FileModel = require("../modules/file");
exports.uploadFile = [
    upload.single('file'),
    async function(req, res){
        try {
            console.log(' req.body', req.userId,req.body,req.file)
            const { fileName , chunkIndex,totalChunks} = req.body
            const file = req.file
            const filePath = path.join(__dirname, `../file`,fileName)
            // 将文件块追加到文件中
            await fs.promises.appendFile(filePath, file.buffer) // multer 规范

            if (parseInt(chunkIndex) === parseInt(totalChunks) - 1) {
                const fileSize = fs.statSync(filePath).size;
                const fileType = fileName.split('.')[1] //mime.extension(file.mimetype);
                const fileUrl = `/file/${fileName}`;
                const queryFile = new FileModel({userId:req.userId, fileName ,fileSize, fileType,fileUrl});
                await queryFile.uploadFile()
            }
            res.status(200).send('Chunk uploaded successfully');
        }catch (error) {
            console.error('上传失败:', error);
            res.status(500).send('上传失败');
        }
    }
]
exports.downloadFile = async function(req, res){
    try {
        const fileInfo = await FileModel.downloadFile(req.params?.id)
        console.log('downloadFile fileInfo',fileInfo)
        if (!fileInfo) {
            return res.status(404).send('文件未找到');
        }
        const filePath = path.join(__dirname, '../file', fileInfo.fileName);
        res.download(filePath);
    }catch (error){
        console.error('下载失败:', error);
        res.status(500).send('下载失败')
    }
}
exports.deleteFile = async function(req, res){
    const queryFile = new FileModel({id:req.params?.id})
    const fileInfo = await queryFile.deleteFile()
    res.send(fileInfo);
}
exports.getFileList = async function(req, res){
    const queryFile = new FileModel({userRole:req.userRole,userId:req.userId, query:req.query})
    const fileInfo = await queryFile.getFileList()
    res.send(fileInfo);
}
